import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_wan_android/arch/net/http_manager.dart';
import 'package:flutter_wan_android/arch/net/result_data.dart';
import 'package:flutter_wan_android/model/article.dart';
import 'package:flutter_wan_android/res/theme.dart';
import 'package:flutter_wan_android/widget/article_item.dart';
import 'package:flutter_wan_android/widget/refresh.dart';
import 'package:flutter_wan_android/widget/wan_appbar.dart';
import 'package:fluttertoast/fluttertoast.dart';

class MyCollect extends StatefulWidget {
  @override
  _MyCollectState createState() => _MyCollectState();
}

class _MyCollectState extends State<MyCollect> {
  List<Article> _articles = [];

  EasyRefreshController _controller = EasyRefreshController();

  var _pageIndex = 0;

  @override
  void initState() {
    super.initState();
    _getArticles();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WanAppbar(
        context,
        titleStr: "我的收藏",
      ),
      body: Container(
        color: wTheme.background,
        child: EasyRefresh(
          controller: _controller,
          enableControlFinishLoad: true,
          enableControlFinishRefresh: true,
          header: refreshHeader,
          footer: refreshFooter,
          firstRefresh: true,
          child: _getList(),
          onRefresh: () async {
            _pageIndex = 0;
            _getArticles();
          },
          onLoad: () async {
            _getArticles();
          },
        ),
      ),
    );
  }

  _getList() {
    if (_articles.isEmpty) return Container();

    return ListView.builder(
      itemBuilder: (BuildContext context, int index) {
        return ArticleItem(
          _articles[index]..collect = true,
          onRefresh: () {
            setState(() {
              _articles.removeAt(index);
            });
          },
        );
      },
      itemCount: _articles.length,
    );
  }

  /// 获取文章列表
  _getArticles() async {
    ResultData result = await HttpManager.instance()
        .get("lg/collect/list/${_pageIndex}/json", withLoading: false);

    _controller.finishRefresh();
    bind(_controller, result);

    if (result.success) {
      setState(() {
        if (_pageIndex == 0) {
          _articles = getArticleList(result.data["datas"]);
        } else {
          _articles.addAll(getArticleList(result.data["datas"]));
        }
      });
      _pageIndex++;
    } else {
      Fluttertoast.showToast(msg: result.msg);
    }
  }
}
